<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>

      <el-row>
        <el-col :span="4">
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="rolesList" border stripe >
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 这里使用了动态绑定类名，当 index1 等于0 设置类名 -->
            <el-row :class="['bd-bottom','vertical-center',index1===0?'bd-top':'']"
              v-for="(item1,index1) in scope.row.children" :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                  {{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 二级，三级权限 -->
              <el-col :span="19">
                <el-row :class="['vertical-center', index2===0?'':'bd-top']"
                  v-for="(item2,index2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">
                      {{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="(item3) in item2.children" :key="item3.id" type="warning"
                      closable @close="removeRightById(scope.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作" width="320px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini"
              @click="showRightDialog(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%"
      @close="closeRightDialog">
      <!-- 树形菜单   node-key="id" 指定每个节点的id -->
      <el-tree ref="treeRef" :data="rightsTree" :props="defaultProps" node-key="id"
        :default-checked-keys="defKeys" show-checkbox default-expand-all>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { log } from 'util'
export default {
  data() {
    return {
      rolesList: [],
      // 控制显示分配权限对话框显示与否
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsTree: [],
      // 定义树形菜单属性，遍历的子节点属性，标签名属性
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 树中默认勾选的节点id数组
      defKeys: [],

      // 角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色信息（下属所有权限信息）
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message.error('获取角色失败')
      }
      this.rolesList = res.data
    },

    // 根据id删除权限
    removeRightById(role, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // console.log(roleId, rightId)
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}/`
          )

          if (res.meta.status !== 200) {
            console.log(res.meta.msg)
            return this.$message.error('删除权限失败')
          }

          this.$message.success('删除权限成功')

          // 重新渲染整个表格数据，会导致表格展开的列关闭，所以建议不要重新渲染，只给data赋值（当前角色权限）就行
          // this.getRolesList()
          role.children = res.data
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 关闭分配权限对话框
    closeRightDialog() {
      this.defKeys = []
    },
    // 显示分配权限对话框
    showRightDialog(role) {
      // 设置当前执行的角色id，在确定更新权限时要这个id
      this.roleId = role.id

      // 获取所有权限数据
      this.getRightsTree()

      // 获取默认勾选数组
      this.getLeafKeys(role, this.defKeys)

      this.setRightDialogVisible = true
    },

    // 获取树形所有权限（默认全部的权限节点）
    async getRightsTree() {
      const { data: res } = await this.$http.get('rights/tree')

      if (res.meta.status !== 200) {
        return this.$message.error('获取权限失败')
      }
      this.rightsTree = res.data
    },

    // 递归函数  获取三级权限项 （获取当前角色包含的权限）
    getLeafKeys(node, arr) {
      // 如果当前节点不包含 child 属性，那么他是三级权限项，加入到 defKeys 数组
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },

    // 对话框确定按钮-分配权限
    async allotRights(role) {
      this.setRightDialogVisible = false

      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('设置权限失败')
      }

      this.$message.success('设置权限成功')
      this.getRolesList()

      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}

.bd-top {
  border-top: 1px solid #ccc;
}
.bd-bottom {
  border-bottom: 1px solid #ccc;
}

// 让标签垂直居中
.vertical-center {
  display: flex;
  align-items: center;
}
</style>